package org.hrqing.authorization.security;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.springframework.security.oauth2.core.OAuth2AccessToken;
import org.springframework.security.oauth2.core.OAuth2RefreshToken;
import org.springframework.security.oauth2.server.authorization.OAuth2TokenType;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;
import org.springframework.security.oauth2.server.authorization.settings.TokenSettings;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenContext;
import org.springframework.security.oauth2.server.authorization.token.OAuth2TokenGenerator;

import java.time.Duration;
import java.time.Instant;
import java.util.UUID;

/**
 * @auther Hrqing
 */
public class RandomRefreshTokenGenerator implements OAuth2TokenGenerator<OAuth2RefreshToken> {

    @Override
    public OAuth2RefreshToken generate(OAuth2TokenContext context) {
        if (context.getTokenType() != null && context.getTokenType() == OAuth2TokenType.REFRESH_TOKEN) {
            RegisteredClient registeredClient = context.getRegisteredClient();
            TokenSettings tokenSettings = registeredClient.getTokenSettings();

            // 获取令牌有效期
            Duration tokenLifetime = tokenSettings.getRefreshTokenTimeToLive();

            String tokenValue = UUID.randomUUID().toString().replaceAll("-", "");

            return new OAuth2RefreshToken(
                    tokenValue,
                    Instant.now(),
                    Instant.now().plus(tokenLifetime)
            );
        }
        return null;
    }
}
